//引入对象
const Koa = require('koa');
const Router = require('koa-router');
const koaBody =require('koa-body');
const tagRouter = require("./routers/tag.router");
const userRouter = require("./routers/user.router")
const contentRouter = require("./routers/content.router")
const jwtPRputer = require("./routers/jwttest.router");
const { fail } = require("./toast");
const jwt = require("jsonwebtoken");
const key = "web";
//引入内部方法或属性
//const {方法或属性名} =require('koa');
const app = new Koa();
app.use(koaBody({
    strict:false
}));

app.use(async (ctx, next) =>{
    const exp = [
        '/login',
        '/',
        'register',
    ];//不需要验证的地址
  if(exp.includes(ctx.url))
  {
    await next();
      return;
  }

    console.log(ctx.headers)
    const authorization=ctx.headers.authorization;
    if(!authorization){
        return fail(ctx, "请添加 token 信息");
    }
    const token = authorization.split(' ')[1];
    try{
      const user= jwt.verify(token, key);
      if(user.name=== "admin") {
       await next();
      }else{
          return fail(ctx,"权限不足");
      }
    } catch (error) {
  return fail(ctx, error);
    }
})

const router = new Router();//创建路由，支持传递参数
tagRouter(router);
userRouter(router);
contentRouter(router);
jwtPRputer(router);


// 调用router.routes()来组装匹配好的路由，返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件，当发送了不符合的请求时，会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
 app.use(router.routes()).use(router.allowedMethods());

    // throw: true, // 抛出错误，代替设置响应头状态
    // notImplemented: () => '不支持当前请求所需要的功能',
    // methodNotAllowed: () => '不支持的请求方式'



//localhost:3000
app.listen(3000,()=>{
    console.log("http://localhost:3000")
});